package cn.koala.key.common.excel;

import cn.koala.key.common.excel.easyexcel.listener.ExcelListener;
import cn.seed.common.core.ResultCode;
import cn.seed.common.core.ServiceException;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description:Excel工具类
 * @author:方典典
 * @time:2018/10/30 10:55
 */
public class ExcelUtils {

    private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
    /**
     * @param type
     * @param data
     * @return void
     * @Description:Excel导出
     * @exception:
     * @author: 方典典
     * @time:2018/10/30 11:06
     */
    public static <T> void export(OutputStream outputStream,ExcelTypeEnum type, List<T> data,Class<T> c) {
        ExcelWriterBuilder excelWriterBuilder = new ExcelWriterBuilder();
        excelWriterBuilder.file(outputStream).head(c).excelType(type).sheet(1).doWrite(data);
    }

    /**
     * 设置响应头参数
     * @param response
     * @param name 要导出的Excel的名称
     * @throws UnsupportedEncodingException
     */
    public static void setResponse(HttpServletResponse response, String name) throws UnsupportedEncodingException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name+".xlsx", "UTF-8"));
    }

    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass, Integer sheetNo) throws Exception {
        ExcelListener<T> listener = new ExcelListener<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ExcelReader excelReader = EasyExcel.read(inputStream, pojoClass, listener).build();
            ReadSheet readSheet = EasyExcel.readSheet(sheetNo).build();
            excelReader.read(readSheet);
            // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
            excelReader.finish();
        } catch (IOException e) {
            logger.error("IOException",e);
        }finally {
            if (inputStream != null){
                inputStream.close();
            }
        }
        return listener.getData();
    }

    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws Exception{
        ExcelListener<T> listener = new ExcelListener<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ExcelTypeEnum excelTypeEnum = file.getOriginalFilename().endsWith(ExcelTypeEnum.XLS.getValue()) ? ExcelTypeEnum.XLS : ExcelTypeEnum.XLSX;
            EasyExcelFactory.read(inputStream, pojoClass, listener).excelType(excelTypeEnum).sheet().doRead();
        } catch (IOException e) {
            throw new ServiceException(ResultCode.DATA_ERROR, "excel解析异常，请对照模板");
        } catch (Exception e) {
            throw new ServiceException(ResultCode.DATA_ERROR, e.getMessage());
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return listener.getData();
    }

    public static <T> void exportExcel(HttpServletResponse response, Class<T> pojoClass, List<T> dataList, String fileName) throws Exception {
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            setResponse(response, fileName);
            // 默认导出xlsx
            EasyExcelFactory.write(outputStream,pojoClass).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(dataList);
        } catch (IOException e) {
            throw new ServiceException(ResultCode.DATA_ERROR, "excel导出异常");
        } catch (Exception e) {
            throw new ServiceException(ResultCode.DATA_ERROR, e.getMessage());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}
